package esi.t2no1.jobs;

import java.text.Format;
import java.text.SimpleDateFormat;

import org.project.t2rk2.ParseException_Exception;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import esi.t2no1.dao.meterdata.MeterDataDAO;
import esi.t2no1.dao.meterdata.MeterDataDTO;
import esi.t2no1.ws.Ws;

/**
 * @author Reimo Rebane
 */
public class ReportMeterDataJob extends QuartzJobBean {

	private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory
			.getLogger(ReportMeterDataJob.class);

	@Override
	protected void executeInternal(JobExecutionContext ctx)
			throws JobExecutionException {

		Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		MeterDataDAO meterDataDAO = (MeterDataDAO) ctx.getJobDetail()
				.getJobDataMap().get("meterDataDao");

		// Send metering data of T2ES1
		MeterDataDTO mdes1 = meterDataDAO.getLatestMeterData("T2ES1");
		if (mdes1 != null) {
			System.out.println("Send metering data of T2ES1");
			// To T2ES1
			Ws.T2ES1.sendMeteringReadings(mdes1.toES1MeterData());

			// To T2RK1
			Ws.T2RK1.receiveDailyMeteredData(Ws.NETWORK_OWNER_ID,
					mdes1.getAreaId(), formatter.format(mdes1.getReadTime()),
					formatter.format(mdes1.getReadTime()),
					mdes1.getFacilityId(), mdes1.getReadValue(), "T2ES1",
					mdes1.getReadValue());

			// To T2RK2
			try {
				Ws.T2RK2.saveMeteredData(formatter.format(mdes1.getReadTime()),
						formatter.format(mdes1.getReadTime()), new String("1"),
						mdes1.getFacilityId(), Ws.NETWORK_OWNER_ID, new String(
								"T2ES1"), mdes1.getFacilityId(), mdes1
								.getAreaId());
			} catch (ParseException_Exception e) {
				LOG.error("Failed to parse metering data to T2RK2 message format");
			}
		}

		// Send metering data of T2ES2
		MeterDataDTO mdes2 = meterDataDAO.getLatestMeterData("T2ES2");
		if (mdes2 != null) {
			System.out.println("Send metering data of T2ES2");
			// To T2ES2
			try {
				Ws.T2ES2.submitMeterData(mdes2.toES2MeterData());
			} catch (Exception e) {
				LOG.error("Failed to parse metering data to T2ES2 message format");
			}

			// To T2RK1
			Ws.T2RK1.receiveDailyMeteredData(Ws.NETWORK_OWNER_ID, mdes2
					.getAreaId(), formatter.format(mdes2.getReadTime()), formatter.format(mdes2
					.getReadTime()), mdes2.getFacilityId(), mdes2
					.getReadValue(), "T2ES2", mdes2.getReadValue());

			// To T2RK2
			try {
				Ws.T2RK2.saveMeteredData(formatter.format(mdes2.getReadTime()),
						formatter.format(mdes2.getReadTime()), "1", "2",
						Ws.NETWORK_OWNER_ID, "T2ES2", mdes2.getFacilityId(),
						mdes2.getAreaId());
			} catch (ParseException_Exception e) {
				LOG.error("Failed to parse metering data to T2RK2 message format");
			}
		}
	}
}
